package com.kobeliu.strategy;

import com.kobeliu.enums.BizCodeEnum;
import com.kobeliu.exception.BizException;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class CustomPreciseShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    /**
     *
     * @param collection   ----  数据源的集合
     *                     分库时值为所有分片库的集合 ds0，ds1，ds2
     *                     分表时为 对应分库中所有分表的集合 short_link_0,short_link_1
     * @param preciseShardingValue  ---- 分片属性
     *                              logicTableName 逻辑表
     *                              columnName 分片键（字段）
     *                              value 从SQL中解析出来的分片键的值
     * @return
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {
        // 0,1,2 sdsfs
        //sql对应字段的第一位字段与ds$对应
        String substring = preciseShardingValue.getValue().substring(0, 1);

        for(String name:collection){
            //ds0,1,2
            String suffix = name.substring(name.length()-1);
            if(suffix.equals(substring)){
                return name;
            }
        }

        //抛异常
        throw new BizException(BizCodeEnum.DB_ROUTE_NOT_FOUND);

    }
}
